﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace APICommond
{
    public class DatasetToJson
    {
        public static string DataToJson(DataTable table)
        {
            string json = "{\"cols\":\"";
            json += GetDataCol(table) + "\",";
            if (table.Rows.Count > 0)
            {
                json += "\"data\":[";
                foreach (DataRow row in table.Rows)
                {
                    json += "{";
                    foreach (DataColumn col in table.Columns)
                    {
                        json += "\"" + col.ColumnName + "\":\"" + row[col].ToString() + "\",";
                    }
                    json = json.Substring(0, json.Length - 1);
                    json += "},";
                }
                json = json.Substring(0, json.Length - 1);
                json += "]}";
            }
            else
            {
                json += "\"data\":\"\" }";
            }
            return json;
        }

        public static string GetDataCol(DataTable table)
        {
            string cols = "";
            foreach (DataColumn col in table.Columns)
            {
                cols += col.ColumnName + ",";
            }
            cols = cols.Substring(0, cols.Length - 1);
            return cols;
        }


      
    }
}
